package com.lagou.rocketmq.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class RocketMQProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Value("${rocketmq.producer.send-message-timeout}")
    private Integer messageTimeOut;

    /**
     * 发送普通消息
     */
    public void sendMsg(String message){
        rocketMQTemplate.syncSend("ef-upload-video", message);
    }

    /**
     * 发送异步消息 在SendCallback中可处理相关成功失败时的逻辑
     */
    public void sendAsyncMsg(String message){
        rocketMQTemplate.asyncSend("ef-upload-video", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("------发送订单消息成功！");
            }
            @Override
            public void onException(Throwable e) {
                log.info("------发送订单消息失败！");
            }
        });
    }

    /**
     * 发送延时消息<br/>
     * 在start版本中 延时消息一共分为18个等级分别为：1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h<br/>
     */
    public void sendDelayMsg(String message, Integer delayLevel){
        rocketMQTemplate.asyncSend("queue_order_delay_topic",
                MessageBuilder.withPayload(message).build(),
                new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        log.info("------发送延迟消息成功！");
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        log.info("------发送延迟消息失败！");
                    }
                },
                messageTimeOut,
                delayLevel);
    }

    /**
     * 发送带tag的消息,直接在topic后面加上":tag"
     */
    public void sendTagMsg(String message){
        rocketMQTemplate.syncSend("queue_test_topic:tag1", message);
    }

}
